const jwt = require("jsonwebtoken");
const { User } = require("../models");
const { Unauthorized } = require('http-errors');
const { success,failure } = require("../utils/response");

module.exports = async(req,res,next)=>{
    try {
        // 取出token 并判断token是否存在
        const {token} = req.headers
        
        if(!token){
            throw new Unauthorized("没有权限")
        }
        // 验证token是否正确
        const decoded = jwt.verify(token,process.env.SECRET)
        if(!decoded){
            throw new Unauthorized("token验证失败")
        }
        // 查询当前用户
        const user = await User.findByPk(decoded.userId)
        if(!user){
            throw new Unauthorized("用户不存在")
        }
        // 验证当前用户是否是管理员
        if(user.role != 100){
            throw new Unauthorized("没有权限")
        }
        // 将user挂载到req上
        req.user = user
        // 继续执行下一个中间件
        next()
    } catch (error) {
        failure(res,error)
    }
}